import torch
import torch.nn as nn
from torch.nn import functional as F




# 定义残差块ResBlock
class ResidualBlock(nn.Module):
    def __init__(self, inchannel, outchannel, stride=1):
        super(ResidualBlock, self).__init__()
        # 这里定义了残差块内连续的2个卷积层
        self.left = nn.Sequential(
            nn.Conv2d(inchannel, outchannel, kernel_size=3, stride=stride, padding=1, bias=False),
            nn.BatchNorm2d(outchannel),
            nn.ReLU(inplace=True),
            nn.Conv2d(outchannel, outchannel, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(outchannel)
        )
        self.shortcut = nn.Sequential()
        if stride != 1 or inchannel != outchannel:
            # shortcut，这里为了跟2个卷积层的结果结构一致，要做处理
            self.shortcut = nn.Sequential(
                nn.Conv2d(inchannel, outchannel, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(outchannel)
            )

    def forward(self, x):
        out = self.left(x)
        # 将2个卷积层的输出跟处理过的x相加，实现ResNet的基本结构
        residual_out = out + self.shortcut(x)
        # vit = VisionTransformer(
        #     image_size=(224, 224),
        #     patch_size=(16, 16),
        #     emb_dim=residual_out.shape[1],
        #     mlp_dim=1024,
        #     num_heads=6,
        #     num_layers=2,
        #     num_classes=7,
        #     attn_dropout_rate=0.0,
        #     reapet_h=residual_out.shape[-1],
        #     first_cnn_channel = int(residual_out.shape[1]),
        #     dropout_rate=0.2)
        # vit.to('cuda:0')
        # # print("%%%%%%%%%%%% residual_out{} ".format(residual_out.shape))
        # vit_pred  = vit(out)
        # # print("%%%%%%%%%%%% vit_pred {} ".format(vit_pred.shape))
        # final_result = vit_pred*residual_out
        # print("%%%%%%%%%%%% residual_out{} ".format(residual_out.shape))
        out = F.relu(residual_out)
        # print("%%%%%%%%%%%% out{} ".format(out.shape))


        return out

# 定义残差块SeNet Block
class SeNetBlock(nn.Module):
    def __init__(self, inchannel):
        super(SeNetBlock, self).__init__()
        self.avg_pool = nn.AdaptiveAvgPool2d(1)
        self.fc1 = nn.Linear(inchannel, inchannel//8)
        self.fc2 = nn.Linear(inchannel//8, inchannel)
        self.Relu = nn.ReLU(inplace=True)
        self.Sigmoid = nn.Sigmoid()
        
    def forward(self, x):
        # print(x.size())
        out = self.avg_pool(x)
        out = out.view(x.size(0),-1)
        # print(self.fc1)
        out = self.fc1(out)
        # print(out.size())
        out = self.Relu(out)
        out = self.fc2(out)
        # print(out.size())
        out = self.Sigmoid(out)


        return out.unsqueeze(-1).unsqueeze(-1)*x


class ResNet18(nn.Module):
    def __init__(self, num_classes=10):
        super(ResNet18, self).__init__()
        self.inchannel = 64
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU()
        )
        self.conv2 = nn.Sequential(
            nn.Conv2d(960, 512, kernel_size=3, stride=1, bias=False),
            nn.BatchNorm2d(512),
            nn.ReLU()
        )
        self.layer1 = self.make_layer(ResidualBlock, 64, 2, stride=2)
        self.layer2 = self.make_layer(ResidualBlock, 128, 2, stride=2)
        self.layer3 = self.make_layer(ResidualBlock, 256, 2, stride=2)
        self.layer4 = self.make_layer(ResidualBlock, 512, 2, stride=2)
        self.cnn = nn.Conv2d(512, 7, kernel_size=1, stride=1, padding=1)
        # self.layer5 = self.make_layer(ResidualBlock, 1024, 2, stride=2)
        self.fc = nn.Linear(512, num_classes)
        self.SeNet1 = SeNetBlock(64)
        self.SeNet2 = SeNetBlock(128)
        self.SeNet3 = SeNetBlock(256)
        self.SeNet4 = SeNetBlock(512)

        


    # 这个函数主要是用来，重复同一个残差块
    def make_layer(self, block, channels, num_blocks, stride):
        strides = [stride] + [1] * (num_blocks - 1)
        # print("%%%%%%%%%%%%% strides {} %%%%%%%%%%%".format(strides))
        layers = []
        for stride in strides:
            layers.append(block(self.inchannel, channels, stride))
            self.inchannel = channels
        return nn.Sequential(*layers)

    def forward(self, x):
        # 在这里，整个ResNet18的结构就很清晰了
        conv1_out = self.conv1(x)
        res_block1 = self.layer1(conv1_out)
        # print("%%%%%%%%%%%%% res_block1.shape{} %%%%%%%%%%%".format(res_block1.shape))
        # SeNet for Res_block1
        res_block1 = self.SeNet1(res_block1)

        res_block2 = self.layer2(res_block1)
        res_block2 = self.SeNet2(res_block2)
        # print("%%%%%%%%%%%%% res_block2.shape{} %%%%%%%%%%%".format(res_block2.shape))
        res_block3 = self.layer3(res_block2)
        res_block3 = self.SeNet3(res_block3)
        # print("%%%%%%%%%%%%% res_block3.shape{} %%%%%%%%%%%".format(res_block3.shape))
        res_block4 = self.layer4(res_block3)
        res_block4 = self.SeNet4(res_block4)
        # print("%%%%%%%%%%%%% res_block4.shape{} %%%%%%%%%%%".format(res_block4.shape))
        out = res_block4

        out1 = self.cnn(res_block4)
        # print("%%%%%%%%%%%%% out.shape{} %%%%%%%%%%%".format(out.shape))
        out1 = F.adaptive_avg_pool2d(out1, (1,1))
        
        out1 = out1.view(out1.size(0), -1)
        # out1 = torch.softmax(out1, dim=-1)
        # print("%%%%%%%%%%%%% out1.shape{} %%%%%%%%%%%".format(out1))
        out = F.adaptive_avg_pool2d(out, (1,1))
        out = out.view(out.size(0), -1)
        # print("%%%%%%%%%%%%% out.shape{} %%%%%%%%%%%".format(out.shape))
        out = self.fc(out)
        out = out+out1
        # print("%%%%%%%%%%%%% out.shape{} %%%%%%%%%%%".format(out.shape))
        return out


# net = ResNet18(num_classes=7)
# x = torch.randn((64, 3, 128, 128))
# # net(x)
# out = net(x)
# print(out.size())